package com.guagua.chat.room;

/**
 * 北京八度互联科技有限公司版权所有
 * Copyright (C) Badu Corporation. All Rights Reserved
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;

import me.prettyprint.cassandra.serializers.StringSerializer;
import net.sf.json.JSONArray;
import net.sf.json.JSONDynaBean;
import net.sf.json.JSONObject;

import com.guagua.chat.active.Active;
import com.guagua.chat.active.ActiveManager;
import com.guagua.chat.base.BaseAction;
import com.guagua.chat.photo.Photo;
import com.guagua.chat.star.Star;
import com.guagua.chat.star.StarManager;
import com.guagua.chat.top.TopDao;
import com.guagua.upload.UploadClient;
import com.guagua.user.UserManager;
import com.guagua.util.CassandraClient;
import com.guagua.util.IpAddrAndMAC;
import com.guagua.vas.constants.CacheConstants;
import com.guagua.vas.constants.ConfigConstants;
import com.guagua.vas.redis.RedIsHandlerFactory;
import com.guagua.vas.util.CacheManager;
import com.guagua.vas.util.DateUtil;
import com.guagua.vas.util.HTTPUtil;
import com.guagua.vas.util.StringUtil;

/*******************************************************************************
 * 类概要:首页action类
 * 
 * @author 白云鹏
 * @version 2012年7月31日10:11:39
 ******************************************************************************/
public class ChatRoomAction extends BaseAction {
	
	// 明星对象
	private Star star;
	// 图片对象
	private Photo photo;
	// 活动对象
	private Active active;
	// 房间对象
	private ChatRoomInfo room;
	private long roomid;
	private long oemid;
	private int currentPage;
	private long activeid;
	private int sorttype;
	private long starId;
	private int sort;
	private long userid;
	private Long[] des_room_id;
	private long srcRoomid;
	private long desRoomid;
	private String starUid;

	private String filename;// 附件名称
	private long fileid;// 附件ID
	private String fileURL;// 附件地址
	
	private int isListStarPage;


	
	private boolean isLogin() {
		if (this.getUserId() <= 0) {
			return false;
		}
		return true;
	}

	/**
	 * 函数说明：首页所需数据 <br/>
	 * 
	 * @return 返回结果说明. （String）跳转界面/index.jsp
	 * @throws ParseException
	 */
	// 首页查询
	public String index() {
		final long uid = this.getUserId();
		// System.out.println("uid:"+uid);
		final Long room_id = roomid;
		final ChatRoomManager mgr = ChatRoomManager.getInstance();
		if (uid != -1) {// 说明登录过。
			new Thread(new Runnable() {// 单开一个线程去处理 判断是否需要添加记录。
						public void run() {
							synchronized (this) {
								if (!ChatRoomUtil.checkLoginRoomInfo(uid,roomid)) {
									ChatRoomUtil.putLoginRoomInfo(uid, roomid);// 添加缓存，记忆
									// 添加数据库信息。
									mgr.addRoomLoginLog(uid, room_id,IpAddrAndMAC.getInstance().getIpAddr(request));
								}
							}
						}
					}).start();
		}
		StarManager stMgr = StarManager.getInstance();
		ActiveManager acMgr = ActiveManager.getInstance();
		List roomInfo = mgr.getRoomInfo(room_id, uid);
		// 通过房间获取房间是自动还是手动排序明星推荐 开始
		boolean isRandom = true;
		if (roomInfo != null) {
			Map m = (Map) roomInfo.get(0);
			try {
				Integer sortTypeInteger = Integer.parseInt(String.valueOf(m.get("sort_type")));
				if (sortTypeInteger != 0) {
					isRandom = false;
				}
			} catch (Exception e) {
				logger.debug(e.getMessage());
				isRandom = false;
			}
		}
		// 通过房间获取房间是自动还是手动排序明星推荐 结束

		// 获取明星，如果集合为空，则调用明星体系接口，去获取明星变化情况，并填充到数据库中。
		List starInfo = stMgr.listStar(1, 16, room_id);
		threadChangeStar(starInfo, room_id);
		starInfo = randomStarInfo(room_id, starInfo, isRandom);
		List activeInfo = (List) acMgr.listActive(1, 5, room_id, request.getCookies(), uid, response);
		String tempObject = String.valueOf(activeInfo.get(1));
		Map map = (Map) JSONObject.toBean(JSONObject.fromObject(tempObject.substring(1, tempObject.length())), HashMap.class);
		// mgr.getOnlineWeekAndMaster(roomid, uid);// 获取室主和房间信息值
		request.setAttribute("roomInfo", roomInfo);
		request.setAttribute("starInfo", starInfo);
		request.setAttribute("starInfoSize", starInfo.get(0).toString().equals("[]") ? 0 : 1);

		List<Map> activeInfos = (List<Map>) activeInfo.get(0);
		List<Map> tempList = new ArrayList<Map>();
		for (Map tm : activeInfos) {
			if (!String.valueOf(tm.get("period")).equals("2")) {
				tempList.add(tm);
			} else {
				break;
			}
		}
		if (tempList.size() == 0) {
			if(activeInfos.size()>0){
				tempList.add(activeInfos.get(0));
			}else{
				tempList = activeInfos;
			}
		}
		request.setAttribute("activeInfo", tempList);

		request.setAttribute("activeInfoCount", map.get("totalRecords"));
		request.setAttribute("userid", uid);
		request.setAttribute("roomid", room_id);
		//request.getSession().setAttribute("oemid", oemid);
		return "LIST";

	}

	/**
	 * 函数说明：如果明星房间数据库中无数据，则调用接口，获取明星变化情况存入数据库中。<br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public void getChangeStar(long room_id, long currTime) {
		// room_id = 381640;
		Map<String, String> msg = new HashMap();
		String url = "http://star.17guagua.com/external/findStarInfoListByRoomId.jspa";
		msg.put("roomId", String.valueOf(room_id));
		String result = HTTPUtil.post(url, msg);
		if (result == null) {
			return;
		}
		StarManager stMgr = StarManager.getInstance();
		try {
			result = URLDecoder.decode(result, "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.debug(e.getMessage());
		}
		JSONObject jObject = JSONObject.fromObject(result);
		JSONArray job1 = (JSONArray) jObject.get("message");
		List list = JSONArray.toList(job1);
		List<Star> stars = new ArrayList<Star>();
		List<Long> starLongs = new ArrayList<Long>();
		for (Object object : list) {
			// starLevel=17, starJobName=歌手, nickName=ok, roomName=吴元元财经测试房间,
			// roomId=381640, starJobId=1, starLevelName=知名艺人, starId=35449143
			Star obj = new Star();
			obj.setCreate_time(currTime);
			obj.setLevel(Integer.parseInt(String.valueOf(((JSONDynaBean) object).get("starLevel"))));
			obj.setStarJobId(Integer.parseInt(String.valueOf(((JSONDynaBean) object).get("starJobId"))));
			// obj.setId();//自动增长
			obj.setIntroduce(String.valueOf(((JSONDynaBean) object).get("starLevelName")));
			obj.setRoom_id(room_id);
			obj.setSort(0);
			obj.setUser_id(Long.parseLong(String.valueOf(((JSONDynaBean) object).get("starId"))));
			String nickName = "";
			try {
				nickName = UserManager.getInstance().getNickname(obj.getUser_id());
			} catch (Exception e) {
				logger.debug(e.getMessage());
				nickName = "";
			}
			obj.setNickname(nickName);
			obj.setUrl("http://zone.17guagua.com/" + obj.getUser_id());
			// obj.setFace((long)0);//可以直接根据ID获取头像。
			stars.add(obj);
			starLongs.add(obj.getUser_id());
		}
		//通过判断当前明星数量是否大于16，如果小于则从红人榜中获取明星，补齐16位明星。然后添加入数据库
		stars = getStarsForHRB(room_id,starLongs,stars);	
		stMgr.addStars(stars, room_id, currTime);
		stMgr.delStars(roomid, currTime);
		CacheManager.getInstance().remove(ChatRoomUtil.ROOMSINGER_ROOM_ID(room_id));
		CacheManager.getInstance().remove(ChatRoomUtil.ROOMSINGER_4_ROOM_ID(room_id));
		ChatRoomUtil.removeLEVELICON_ROOM_ID(room_id);
	}
	/**
	 * 通过房间信息获取月排行榜，获取所有的用户ID集合，在获取
	 * Map<Long,Star>  用户MAP集合
	 * 放入集合，凑齐16个明星。
	 * @param room_id
	 * @return
	 */
	private List<Star> getStarsForHRB(long room_id,List<Long> starLongs,List<Star> stars){
		int len = 0 ;
		if(stars==null){len=0;}else{len= stars.size();}
		if(stars.size()>=16){return stars;}else{len = 16-len;}
		TopDao topDao = new TopDao();
		String starString = topDao.getPopularityMonth(room_id+"");
		if(starString==null){return stars;}
		String[] tempStar = starString.split(",");
		int index = 1;
		starString = "";
		//获取明星信息MAP
		Map<Long,Star> starMap  = new HashMap<Long,Star>();
		for(int i=0;i<tempStar.length;i++){
			long tstarId = Long.parseLong(tempStar[i]);
			if(starLongs.contains(tstarId)){continue;}
			Star star = new Star();
			star.setUser_id(tstarId);
			star.setUrl("http://zone.17guagua.com/"+tstarId);
//			star.setLevel(0);
//			star.setFace(0);
//			star.setIntroduce("");
			star.setRoom_id(room_id);
//			star.setSort(0);
			String nickName = "";
			try {
				nickName = UserManager.getInstance().getNickname(tstarId);
			} catch (Exception e) {
				logger.debug(e.getMessage());
				nickName = "";
			}
			star.setNickname(nickName);
			stars.add(star);
			if(len>0&&index==len){
				break;
			}else if(index==16&&len==0){
				break;
			}
			index++;
		}
		return stars;
		
	} 
	
	//   /top!query.jspa?roomId=xx&type=popularity&allottedTime=month

	/**
	 * 随机获取4条数据，还是不随机，按照顺序。
	 * 
	 * @param tempstarInfo
	 * @return
	 */
	private List randomStarInfo(long roomid, List tempstarInfo, boolean isRandom) {
		String key = ChatRoomUtil.ROOMSINGER_4_ROOM_ID(roomid);
		// ChatRoomUtil.removeObj(key);
		Object obj = ChatRoomUtil.getObj(key);
		List starInfo = null;
		if (obj != null) {
			starInfo = (List) obj;
			if (starInfo != null) {
				return starInfo;
			}
		}
		starInfo = new ArrayList();
		List temp = ((List) tempstarInfo.get(0));
		if (temp.size() != 0) {
			if (isRandom) {
				// ////从明星第一页中16条随机获取4条开始////////

				List tstarInfo = new ArrayList();
				int starLen = temp.size();
				if (starLen <= 4) {
					tstarInfo = temp;
				} else {
					Random rm = new Random();
					int tIndex = rm.nextInt(starLen);
					int ti = tIndex;
					for (int i = 0; i < 4; i++) {
						if (ti < 0) {
							ti = 0;
						}
						if (ti < starLen) {
							tstarInfo.add(temp.get(ti));
							ti++;
						} else {
							ti = tIndex;
							ti--;
							tstarInfo.add(temp.get(ti));
						}
					}
				}
				starInfo.add(tstarInfo);
				// ////从明星第一页中16条数据中获取4条结束////////
			} else {
				List tstarInfo = new ArrayList();
				for (int i = 0; i < temp.size(); i++) {
					if (tstarInfo.size() >= 4
							|| tstarInfo.size() == temp.size()) {
						break;
					}
					tstarInfo.add(temp.get(i));
				}
				starInfo.add(tstarInfo);
			}
		} else {
			starInfo.add(tempstarInfo.get(0));
		}
		starInfo.add(tempstarInfo.get(1));
		// starInfo.add(tempstarInfo.get(2));
		ChatRoomUtil.putObj(key, starInfo);
		return starInfo;
	}

	/**
	 * 活动列表
	 * 
	 * @return
	 */
	public String activelist() {
		long uid = this.getUserId();
		Long room_id = roomid;
		request.setAttribute("roomid", room_id);
		ActiveManager acMgr = ActiveManager.getInstance();
		if (currentPage == 0) {
			currentPage = 1;
		}
		List arr = acMgr.listActive(currentPage, 5, room_id, request.getCookies(), uid, response);
		List activeInfo = (List) arr.get(0);
		request.setAttribute("activeInfo", activeInfo);
		request.setAttribute("pageJson", arr.get(1));
		ChatRoomManager mgr = ChatRoomManager.getInstance();
		List list = mgr.getOnlineWeekAndMaster(room_id, uid);// 获取室主和房间信息值
		request.setAttribute("ismaster", list.get(0).toString());
		request.setAttribute("roomname", list.get(2).toString());
		List<RoomVo> roomVoList = mgr.getUserRoom(uid);
		// List<RoomVo> roomVoList = mgr.getUserRoom((long)35444539);
		request.setAttribute("roomVoList", roomVoList);
		request.setAttribute("roomVoListSize", roomVoList.size());
		request.setAttribute("userid", uid);
		return "ACTIVELIST";
	}

	/**
	 * 获取转播信息
	 * 
	 * @return
	 */
	public String getZBInfo() {
		long uid = this.getUserId();
		ChatRoomManager mgr = ChatRoomManager.getInstance();
		List<RoomVo> roomVoList = mgr.getUserRoom(uid);
//		 List<RoomVo> roomVoList = mgr.getUserRoom(35456937);
		// List<RoomVo> roomVoList = mgr.getUserRoom(35456937);
		// List<RoomVo> roomVoList = mgr.getUserRoom(35491795);
		// List<RoomVo> roomVoList = mgr.getUserRoom((long)35444539);
		// //////AJAX 加载 改。
		// 游客不查询，本房间室主不能转播自己的。
		try {
			StringBuilder result = new StringBuilder();
			JSONArray jObject = JSONArray.fromCollection(roomVoList);
			result.append("{roomVoList:").append(jObject.toString()).append(
					",roomVoListSize:").append(roomVoList.size()).append("}");
			PrintWriter out = response.getWriter();
			out.write(result.toString());
		} catch (IOException e) {
			logger.debug(e.getMessage());
			return null;
		}
		return null;
	}

	/**
	 * 进入添加明星页面
	 * 
	 * @return
	 */
	public String toAddStarPage() {
		long uid = this.getUserId();
		ChatRoomManager mgr = ChatRoomManager.getInstance();
		Long room_id = roomid;
		List list = mgr.getOnlineWeekAndMaster(room_id, uid);// 获取室主和房间信息值
		if (Integer.parseInt(list.get(0).toString()) == 0) {// 非室主，需要跳转回去。
			return index();
		} else {
			request.setAttribute("online_week", list.get(1).toString());
		}
		StarManager stMgr = StarManager.getInstance();
		if (currentPage == 0) {
			currentPage = 1;
		}
		List starInfo = stMgr.listStar(currentPage, 16, room_id);
		threadChangeStar(starInfo, room_id);
		System.out.print(starInfo.get(0).toString());
		// if(starInfo.get(0).toString().equals("[]")){
		// return "ERROR";
		// }
		List roomInfo = mgr.getRoomInfo(room_id, uid);
		request.setAttribute("sorttype", ((HashMap) roomInfo.get(0)).get("sort_type"));
		request.setAttribute("starInfo", starInfo);
		return "TOADDSTAR";
	}

	/**
	 * 异步请求获取明星列表页面
	 * 
	 * @param starInfo
	 * @param roomid
	 */
	private void threadChangeStar(final List starInfo, final long room_id) {
		final String cacheKey =ChatRoomUtil.TIMEUNIT_ROOMSTAR_ROOM_ID(room_id);
		String tempString = "";
		Object obj = CacheManager.getInstance().get(cacheKey);
		if (obj == null) {
			List list = (ArrayList) starInfo.get(0);
			for (Object key : list) {
				tempString = ((HashMap) key).get("update_time").toString();
				break;
			}			
			if(!"".equals(tempString)&&System.currentTimeMillis() - Long.parseLong(tempString) >=1000*60*60){
				tempString = "";
			}
		} else {
			tempString = String.valueOf(obj);
		}
		boolean isFlash = false;
		if ("".equals(tempString)) {
			isFlash = true;
		}
//		isFlash = true;
		if (isFlash) {// 时间超过一小时
			// 单开一个线程去处理 明星变化情况
			new Thread(new Runnable() {
				public void run() {

					synchronized (this) {
						// 处理明星变化。
						long currTime = System.currentTimeMillis();
						// 放入缓存，1小时过期
						CacheManager.getInstance().put(cacheKey, currTime, 1,TimeUnit.HOURS);

						getChangeStar(room_id, currTime);
					}
				}
			}).start();
		}
	}

	/**
	 * 进入明星列表页面
	 * 
	 * @return
	 */
	public String starlist() {

		Long room_id = roomid;
		StarManager stMgr = StarManager.getInstance();
		if (currentPage == 0) {
			currentPage = 1;
		}
		List starInfo = stMgr.listStar(currentPage, 16, room_id);
		threadChangeStar(starInfo, room_id);
		// System.out.print(starInfo.get(0).toString());
		// if(starInfo.get(0).toString().equals("[]")){
		// return "ERROR";
		// }
		request.setAttribute("starInfo", starInfo);
		return "STARLIST";
	}

	/**
	 * 进入添加活动页面
	 * 
	 * @return
	 */
	public String toAddActivePage() {
		long uid = this.getUserId();
		ChatRoomManager mgr = ChatRoomManager.getInstance();
		List list = mgr.getOnlineWeekAndMaster(roomid, uid);// 获取室主和房间信息值
		if (Integer.parseInt(list.get(0).toString()) == 0) {// 非室主，需要跳转回去。
			return index();
		} else {
			// request.setAttribute("online_week", 30);
			request.setAttribute("online_week", list.get(1).toString());
		}
		// activeid 活动ID
		request.setAttribute("room_id", roomid);
		request.setAttribute("user_id", uid);
		if (activeid != 0) {
			request.setAttribute("activeid", activeid);
		} else {
			request.setAttribute("activeid", 0);
		}
		return "ACTIVEEDIT";
	}

	/**
	 * 进入活动修改页面
	 * 
	 * @return
	 */
	public String toActiveEdit() {
		long uid = this.getUserId();
		ChatRoomManager mgr = ChatRoomManager.getInstance();
		List list = mgr.getOnlineWeekAndMaster(roomid, uid);// 获取室主和房间信息值
		if (Integer.parseInt(list.get(0).toString()) == 0) {// 非室主，需要跳转回去。
			return index();
		} else {
			request.setAttribute("online_week", list.get(1).toString());
		}
		ActiveManager acMgr = ActiveManager.getInstance();
		if (activeid != 0) {
			request.setAttribute("activeid", activeid);
			request.setAttribute("activeInfo", acMgr.getActiveById(activeid));
		} else {
			request.setAttribute("activeid", 0);
		}
		// activeid 活动ID
		request.setAttribute("room_id", roomid);
		request.setAttribute("user_id", this.getUserId());
		return "ACTIVEEDIT";
	}

	/**
	 * 函数说明：ajax获取房间收藏数量 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String getLocalCache() {
		Map<String, String> msg = new HashMap();
		msg.put("room_id", String.valueOf(roomid));
		msg.put("oemid", String.valueOf(oemid));
		Long timeLong = System.currentTimeMillis();
		msg.put("sk", ChatRoomUtil.strMD5(roomid + ChatRoomUtil.key+ timeLong));
		msg.put("t", String.valueOf(timeLong));
		String result = HTTPUtil.post("http://fav.chat.17guagua.net/favroom/ufra!getRoomFavroomCount.jspa",msg);
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			logger.debug(e.getMessage());
			return null;
		}
		return null;
	}

	/**
	 * 函数说明：ajax获取房间收藏数量 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String addfavroom() {
		long uid = this.getUserId();
		if (uid == -1) {
			System.out.println(0);
			return null;
		}
		Map<String, String> msg = new HashMap();
		msg.put("room_id", String.valueOf(roomid));
		msg.put("uid", String.valueOf(uid));
		Long timeLong = System.currentTimeMillis();
		msg.put("sk", ChatRoomUtil.strMD5(String.valueOf(uid)
				+ ChatRoomUtil.key + timeLong));
		msg.put("t", String.valueOf(timeLong));
		String result = HTTPUtil
				.post(
						"http://fav.chat.17guagua.net/favroom/ufra!addWebUserFavRoom.jspa",
						msg);
		try {
			// System.out.println(result);
			response.getWriter().write(result);
		} catch (IOException e) {
			logger.debug(e.getMessage());
			return null;
		}
		return null;
	}

	/**
	 * 函数说明：ajax请求添加明星 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String addStar() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			StarManager mgr = StarManager.getInstance();
			photo.setCreator(uid);
			if (mgr.addStar(star, photo)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 函数说明：ajax请求删除明星 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String delStar() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			StarManager mgr = StarManager.getInstance();
			if (mgr.delStar(star, photo)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 修改明星顺序
	 * 
	 * @return
	 */
	public String modStarSort() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			StarManager mgr = StarManager.getInstance();
			if (mgr.modStarSort(starId, sort, roomid)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 函数说明：ajax请求添加活动 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String addActive() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			ActiveManager mgr = ActiveManager.getInstance();
//			active.setStart_time(ChatRoomUtil.convertTimeToLong(active.getStartime_str(),""));

			active.setStart_time(DateUtil.date2long(active.getStartime_str(), "yyyy-MM-dd HH:mm"));
			active.setEnd_time(DateUtil.date2long(active.getEndtime_str(), "yyyy-MM-dd HH:mm"));
			//不能同时存在2个已经进行的活动
			int StartCount = mgr.getActiveStartCount(active);
			if(StartCount==-1){//不能小于当前时间
				response.getWriter().write("{result:-3}");
				return null;
			}else if(StartCount>0){//只要大于0 就说明该活动的起始时间在某个活动时间范围内。
				response.getWriter().write("{result:-2}");
				return null;
			}
			Photo file = new Photo();
			file.setPhoto_type_id(3);
			file.setSize_id(3);
			file.setPhoto_name(filename);
			file.setPhoto_path(fileURL);
			if(active.getActive_content().equals("字数限制为0~200个汉字")){active.setActive_content("");}
		 	if (uid > 0 && mgr.addActive(active, photo, uid, file)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			} 
		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 函数说明：ajax请求编辑活动 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String editActive() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			ActiveManager mgr = ActiveManager.getInstance();
			Photo file = new Photo();
			file.setPhoto_type_id(3);
			file.setSize_id(3);
			file.setPhoto_name(filename);
			file.setPhoto_path(fileURL);
			file.setId(fileid);
			if(active.getActive_content().equals("字数限制为0~200个汉字")){active.setActive_content("");}
			active.setStart_time(DateUtil.date2long(active.getStartime_str(), "yyyy-MM-dd HH:mm"));
			active.setEnd_time(DateUtil.date2long(active.getEndtime_str(), "yyyy-MM-dd HH:mm"));
			//不能同时存在2个已经进行的活动
			int StartCount = mgr.getActiveStartCount(active);
			if(StartCount==-1){//不能小于当前时间
				response.getWriter().write("{result:-3}");
				return null;
			}else if(StartCount>0){//只要大于0 就说明该活动的起始时间在某个活动时间范围内。
				response.getWriter().write("{result:-2}");
				return null;
			}
			if (mgr.editActive(active, photo, uid, file)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 函数说明：ajax请求删除活动 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String delActive() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				System.out.println("未登录用户");
				response.getWriter().write("{result:-1}");
				return null;
			}
			ChatRoomManager mgr1 = ChatRoomManager.getInstance();
			List list = mgr1.getOnlineWeekAndMaster(active.getRoom_id(), uid);// 获取室主和房间信息值
			if (Integer.parseInt(list.get(0).toString()) == 0) {// 非室主，需要跳转回去。
				response.getWriter().write("{result:-2}");
				return null;
			}
			ActiveManager mgr = ActiveManager.getInstance();
			if (mgr.delActive(active, photo)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 函数说明：ajax请求添加报名者 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String addJoiner() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			ActiveManager mgr = ActiveManager.getInstance();
			long starTime = active.getStart_time();
			long nowTimeLong = new Date().getTime();
			if(starTime-nowTimeLong<=1000*60*10){// 10分钟之内
				response.getWriter().write("{result:11}");
				return null;
			}
			if(starTime-nowTimeLong<0){// 10分钟之内
				response.getWriter().write("{result:12}");
				return null;
			}
			
			if(!mgr.checkJoiner(active, uid)){
				Cookie joinerStatCookie = new Cookie("joinerStat" + "_"
						+ active.getId() + "_" + active.getRoom_id() + "_"
						+ uid, "0");
				joinerStatCookie.setMaxAge(60 * 60 * 24 * 365);
				response.addCookie(joinerStatCookie);
				response.getWriter().write("{result:0}");
			}else{
				if (uid > 0 && mgr.addJoiner(active, uid)) {
	
					Cookie joinerStatCookie = new Cookie("joinerStat" + "_"
							+ active.getId() + "_" + active.getRoom_id() + "_"
							+ uid, "0");
					joinerStatCookie.setMaxAge(60 * 60 * 24 * 365);
					response.addCookie(joinerStatCookie);
					response.getWriter().write("{result:0}");
				} else {
					response.getWriter().write("{result:-2}");
				}
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
			try {
				response.getWriter().write("{result:\""+e.getMessage()+"\"}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;

	}

	/**
	 * 函数说明：ajax请求编辑房间信息 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String editRoomInfo() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			ChatRoomManager mgr = ChatRoomManager.getInstance();
			if (mgr.editRoomInfo(room, photo, uid)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 修改房间排序类型，室主修改。
	 * 
	 * @return
	 */
	public String modRoomType() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			ChatRoomManager mgr = ChatRoomManager.getInstance();
			if (mgr.udateRoomType(roomid, sorttype)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 函数说明：ajax请求进行图片裁剪 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String cropImg() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}
			// 获得四个坐标点
			String x1 = request.getParameter("x1");
			String y1 = request.getParameter("y1");
			String x2 = request.getParameter("x2");
			String y2 = request.getParameter("y2");
			// 获得缩略图大小
			String[] mw = request.getParameterValues("mw");
			String[] mh = request.getParameterValues("mh");

			// 获得原始图片名称以及地址
			String imgsrc = request.getParameter("imgsrc");
			String ret = UploadClient.selectImage(ConfigConstants.IMG_URL, x1,
					y1, x2, y2, mw, mh, imgsrc);
			response.getWriter().write(ret);
		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 函数说明：ajax请求删除图片 <br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public String delImg() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}

			// 获得原始图片名称以及地址
			String imgsrc = request.getParameter("imgsrc");
			if (!imgsrc.equals(ConfigConstants.IMG_DEFAULT)
					&& !imgsrc.equals("")) {
				String ret = UploadClient.deleteImage(ConfigConstants.IMG_URL,
						imgsrc);
				response.getWriter().write(ret);
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 函数说明：ajax请求获取活动标签 <br/>
	 * 
	 * @return 返回结果说明. （String）json串
	 */
	public String getActiveTag() {
		try {
			long uid = this.getUserId();
			if (uid <= 0) {
				response.getWriter().write("{result:-1}");
				return null;
			}

			String ret = ActiveManager.getInstance().getActiveTag();
			response.getWriter().write(ret);
		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}

	// /**
	// * 函数说明：财经首页所需数据 <br/>
	// *
	// * @return 返回结果说明. （String）跳转界面/caijng_index.jsp
	// */
	// // 首页查询
	// public String roomIndex() {
	// Long room_id = roomid;
	// long uid = this.getUserId();
	// ChatRoomManager mgr = ChatRoomManager.getInstance();
	// StarManager stMgr = StarManager.getInstance();
	// ActiveManager acMgr = ActiveManager.getInstance();
	//
	// List roomInfo = mgr.getRoomInfo(room_id, uid);
	// List starInfo = stMgr.listStar(room_id);
	// List activeInfo = acMgr.getActive(room_id, request.getCookies(), uid,
	// response);
	// request.setAttribute("roomInfo", roomInfo);
	// request.setAttribute("starInfo", starInfo);
	// request.setAttribute("activeInfo", activeInfo);
	// request.setAttribute("userid", uid);
	// return "CJLIST";
	//
	// }

	// /**
	// * 获取用户的转播记录
	// * @param userId
	// * @return
	// * @throws IOException
	// */
	// public String getBroadcastList() throws IOException{
	// AuthToken token = null;
	// long userId = -1;
	// HttpServletRequest request = ServletActionContext.getRequest();
	// HttpServletResponse response = ServletActionContext.getResponse();
	// try {
	// token = AuthFactory.getAuthToken(request, response);
	// userId = token.getUserID();
	// }catch (UnauthorizedException ue) {
	// //logger.error("获取用户信息失败");
	// }
	// userId = 18000;
	// if(userId == -1){
	// PrintWriter out = response.getWriter();
	// out.print("<h2><a href='javascript:void(0);'
	// onclick=\"$('#div_pop_1').hide();\">关闭</a>转播到房间主页</h2>");
	// out.print("<div class='floacont'><ul><li>您当前是<span
	// class='cff7'>游客</span>，请用注册号码登录。</li></ul></div>");
	// out.close();
	// return null;
	// }
	//		
	// //查询用户是否是房主
	// ActiveDao activeDao = new ActiveDao();
	// manager = activeDao.getUserRole(userId);
	// if(manager){
	// //获取房主有哪些房间
	// roomList = activeDao.getUserRoom(userId);
	// if(roomList != null && roomList.size() > 0){
	// //查询用户的转播记录
	// brList = activeDao.getBroadcastList(userId);
	// }
	// }
	// return "getBroadcaseList";
	// }

	/**
	 * 转播
	 * 
	 * @return
	 * @throws IOException
	 */
	public String saveBroadcast() throws IOException {
		long userId = this.getUserid();
		if (userId == -1) {
			PrintWriter out = response.getWriter();
			out.print("您当前是<span class='cff7'>游客</span>，请用注册号码登录。");
			out.close();
			return null;
		}

		if (des_room_id != null && des_room_id.length > 0) {
			ActiveManager mgr = ActiveManager.getInstance();
			for (int i = 0; i < des_room_id.length; i++) {
				TBroadcast br = new TBroadcast();
				br.setDes_room_id(des_room_id[i]);
				br.setActive_id(activeid);
				br.setSrc_room_id(roomid);
				br.setBroadcastor(userId);
				br.setCreate_time(new Date().getTime());
				mgr.saveBroadcast(br);
			}
		}
		return null;
	}

	/**
	 * 获取转播过了哪些活动到哪些房间。
	 * 
	 * @return
	 * @throws IOException
	 */
	public String getBroadcastByUid() throws IOException {
		long userId = this.getUserid();

		if (userId == -1) {
			PrintWriter out = response.getWriter();
			out.print("您当前是<span class='cff7'>游客</span>，请用注册号码登录。");
			out.close();
			return null;
		}
		ActiveManager mgr = ActiveManager.getInstance();
		List<TBroadcast> list = mgr.getBroadcastList(userId, activeid);
		String des_room_ids = "";
		for (TBroadcast tBroadcast : list) {
			des_room_ids += ",'" + tBroadcast.getDes_room_id() + "'";
		}
		if (!des_room_ids.equals("")) {
			response.getWriter().write(
					"{result:\"" + des_room_ids.substring(1) + "\"}");
		} else {
			response.getWriter().write("{result:\"\"}");
		}
		return null;
	}

	/**
	 * 删除转播过来的活动
	 * 
	 * @return
	 * @throws IOException
	 */
	public String zbDelActive() throws IOException {
		long userId = this.getUserid();

		if (userId == -1) {
			PrintWriter out = response.getWriter();
			out.print("您当前是<span class='cff7'>游客</span>，请用注册号码登录。");
			out.close();
			return null;
		}

		try {
			ActiveManager mgr = ActiveManager.getInstance();
			if (mgr.delZbActive(activeid, srcRoomid, desRoomid, userId)) {
				response.getWriter().write("{result:0}");
			} else {
				response.getWriter().write("{result:1}");
			}

		} catch (IOException e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
		}
		return null;

	}


	/**
	 * 获取用户等级
	 * 
	 * @return
	 * @throws IOException
	 */
	public String getLevelIcon() throws IOException {
		long userId = this.getUserid();
		PrintWriter out = response.getWriter();
		if (userId == -1 && starUid.equals("")) {
			out.write("{result:-1}");
			return null;
		}
		try {
			String key = ChatRoomUtil.LEVELICON_ROOM_ID(roomid,isListStarPage);
//			CacheManager.getInstance().remove(key);
			String result =null;
			if(isListStarPage!=0){
				if(currentPage==1){result = String.valueOf(CacheManager.getInstance().get(key));}
				if (result != null && !"null".equals(result.toLowerCase())) {
					out.write(result);
					return null;
				}
			}
			boolean isOk = false;
			String[] tempUids = starUid.split(",");
			String jsonContent = "";
			String levelObjJson = "";
			Map<Long,Star> starMap = findStarInfoList(starUid, System.currentTimeMillis());
			CassandraClient cassandraClient = new CassandraClient();
			for (String uid : tempUids) {
				if(uid.equals("")){continue;}
				try {
					//这个集合  是只有明星才会存在，所以不全
					if(null!=starMap&&starMap.size()!=0){
						Star star = starMap.get(Long.parseLong(uid));
						levelObjJson += "," + uid + ":{level:"+star.getLevel()+",starJobId:"+star.getStarJobId()+ "}";
					}
					//这句话报错，就会出问题，。。
					String json =cassandraClient.getPopularityWeek(uid); 
					if (json == null) {
						jsonContent += uid + "__";
					} else {
						JSONObject jObject = JSONObject.fromObject(json);
						Map map = (Map) JSONObject.toBean(jObject, Map.class);
						String LevelString = "";
						for (Object keyObj : map.keySet()) {
							LevelString += "," + keyObj.toString();
						}
						LevelString = LevelString.substring(1);
						jsonContent += uid + "_" + LevelString + "__";
					}
				} catch (Exception e) {
				
//					logger.debug("111111111111111111111111111110000000000000000"+e.getMessage());
					e.printStackTrace();
//					System.out.println(e.getMessage());
					continue;
				}
			}
			if (!jsonContent.equals("")) {
				jsonContent = "\""+ jsonContent.substring(0, jsonContent.length() - 2)+ "\"";
				isOk = true;
			} else {
				jsonContent = "";
			}
			if (!levelObjJson.equals("")) {
				levelObjJson = "{" + levelObjJson.substring(1) + "}";
				result = "{result:0,content:" + jsonContent + ",levelObjJson:"+ levelObjJson + "}";
			}else{
				result = "{result:0,content:" + jsonContent + "}";
			}
			if (isOk) {
				if(currentPage==1&&isListStarPage!=0){
					CacheManager.getInstance().put(key, result, 5, TimeUnit.MINUTES);// 5分钟刷新下等级图片缓存
				}				
				out.write(result);
			} else {
				out.write("{result:-1}");
			}

		} catch (Exception e) {
			logger.debug(e.getMessage());
//			e.printStackTrace();
			out.write("{result:-1}");
		} finally {
			out.close();
		}
		return null;

	}

	/**
	 * 函数说明：如果明星房间数据库中无数据，则调用接口，获取明星变化情况存入数据库中。<br/>
	 * 
	 * @return 返回结果说明. （String）json串，{result:0}，当为0时，操作成功
	 */
	public Map<Long, Star> findStarInfoList(
			String tstarUid, long currTime) {
		Map<String, String> msg = new HashMap();
		if(tstarUid.equals("")){return new HashMap<Long, Star>();}
		String url = "http://star.17guagua.com/external/findStarInfoList.jspa";
		msg.put("starId", String.valueOf(tstarUid));
		
		String result = HTTPUtil.post(url, msg);
		if (result == null) {
			return null;
		}
		StarManager stMgr = StarManager.getInstance();
		try {
			result = URLDecoder.decode(result, "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.debug(e.getMessage());
		}
		JSONObject jObject = JSONObject.fromObject(result);
		JSONArray job1 = null;
		List list = null;
		try{
			job1 = (JSONArray) jObject.get("message");
			list = JSONArray.toList(job1);
		}catch (Exception e) {
			logger.debug(e.getMessage());
			return new HashMap<Long, Star>();
		}
		Map<Long, Star> map = new HashMap<Long, Star>();
		for (Object object : list) {
			Star star = new Star();
//			star.setCreate_time(currTime);
//			star.setFace(0);
			star.setUser_id(Long.parseLong(String.valueOf(((JSONDynaBean) object).get("starId"))));//明星用户ID
			star.setLevel(Integer.parseInt(String.valueOf(((JSONDynaBean) object).get("starLevel"))));
			try {
				star.setNickname(UserManager.getInstance().getNickname(star.getUser_id()));
			} catch (Exception e) {
				logger.debug(e.getMessage());
				star.setNickname("");
			}
			star.setRoom_id(Long.parseLong(String.valueOf(((JSONDynaBean) object).get("roomId"))));//房间ID
			star.setStarJobId(Integer.parseInt(String.valueOf(((JSONDynaBean) object).get("starJobId"))));//角色			
//			star.setIntroduce(String.valueOf(((JSONDynaBean) object).get("starLevelName")));//简介
//			star.setSort(0);
//			star.setSubject(String.valueOf(((JSONDynaBean) object).get("starJobName")));//主题。。。
//			star.setUrl(url)
			map.put(star.getUser_id(),star);
		}
		return map;
	}

	/**
	 * 进入房间编辑页面
	 * 
	 * @return
	 */
	public String toRoomEdit() {
		Long room_id = roomid;
		long uid = this.getUserId();
		ChatRoomManager mgr = ChatRoomManager.getInstance();
		List list = mgr.getOnlineWeekAndMaster(room_id, uid);// 获取室主和房间信息值
		if (Integer.parseInt(list.get(0).toString()) == 0) {// 非室主，需要跳转回去。
			return index();
		} else {
			request.setAttribute("online_week", list.get(1).toString());
		}
		List roomInfo = mgr.getRoomInfo(room_id, uid);
		request.setAttribute("roomInfo", roomInfo);
		return "TOROOMEDIT";
	}

	public String getRCCount() throws Exception {
		Long room_id = roomid;
		Map<String, String> mapRoomMsg = null;
		mapRoomMsg = RedIsHandlerFactory.getInstance().getGuaguaRoomMsgMap(room_id);
		String activeCount = StringUtil.StringDecodeUtf8(mapRoomMsg.get(CacheConstants.ROOM_USER_COUNT));
		if (activeCount.equals("")) {
			activeCount = "0";
		}
		String result = "{result:0,content:" + activeCount + "}";
		response.getWriter().write(result);
		return null;
	}

	public Star getStar() {
		return star;
	}

	public void setStar(Star star) {
		this.star = star;
	}

	public Photo getPhoto() {
		return photo;
	}

	public void setPhoto(Photo photo) {
		this.photo = photo;
	}

	public Active getActive() {
		return active;
	}

	public void setActive(Active active) {
		this.active = active;
	}

	public ChatRoomInfo getRoom() {
		return room;
	}

	public void setRoom(ChatRoomInfo room) {
		this.room = room;
	}

	public long getRoomid() {
		return roomid;
	}

	public void setRoomid(long roomid) {
		this.roomid = roomid;
	}

	public long getOemid() {
		return oemid;
	}

	public void setOemid(long oemid) {
		this.oemid = oemid;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public long getUserid() {
		return userid;
	}

	public void setUserid(long userid) {
		this.userid = userid;
	}

	public String getStarUid() {
		return starUid;
	}

	public void setStarUid(String starUid) {
		this.starUid = starUid;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public long getFileid() {
		return fileid;
	}

	public void setFileid(long fileid) {
		this.fileid = fileid;
	}

	public String getFileURL() {
		return fileURL;
	}

	public void setFileURL(String fileURL) {
		this.fileURL = fileURL;
	}

	public long getSrcRoomid() {
		return srcRoomid;
	}

	public void setSrcRoomid(long srcRoomid) {
		this.srcRoomid = srcRoomid;
	}

	public long getDesRoomid() {
		return desRoomid;
	}

	public void setDesRoomid(long desRoomid) {
		this.desRoomid = desRoomid;
	}

	public Long[] getDes_room_id() {
		return des_room_id;
	}

	public void setDes_room_id(Long[] des_room_id) {
		this.des_room_id = des_room_id;
	}

	public long getStarId() {
		return starId;
	}

	public void setStarId(long starId) {
		this.starId = starId;
	}

	public int getSort() {
		return sort;
	}

	public void setSort(int sort) {
		this.sort = sort;
	}

	public int getSorttype() {
		return sorttype;
	}

	public void setSorttype(int sorttype) {
		this.sorttype = sorttype;
	}

	public long getActiveid() {
		return activeid;
	}

	public void setActiveid(long activeid) {
		this.activeid = activeid;
	}

	public int getIsListStarPage() {
		return isListStarPage;
	}

	public void setIsListStarPage(int isListStarPage) {
		this.isListStarPage = isListStarPage;
	}

	
}
